package com.etcn.common.utils.email;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.mail.HtmlEmail;
import org.slf4j.LoggerFactory;

import com.etcn.common.pojo.Email;

import ch.qos.logback.classic.Logger;

/**
 * 电子邮件工具
 */
public class MailHandler {
	/**
     * 工具 logger
     */
    protected Logger utilLogger = (Logger) LoggerFactory.getLogger("util_file_log");
    /**
     * 异常logger
     */
    protected Logger errorLogger = (Logger) LoggerFactory.getLogger("error_file_log");
    
	/**
	 * 邮件编码
	 */
	public static final String CHARSET = "utf-8";
	
	/**
	 * 发送方smtp host信息
	 */
	private static Map<String, String> hostMap = new HashMap<String, String>();
	
	static {
		// 126
		hostMap.put("smtp.126", "smtp.126.com");
		// qq
		hostMap.put("smtp.qq", "smtp.qq.com");

		// 163
		hostMap.put("smtp.163", "smtp.163.com");

		// sina
		hostMap.put("smtp.sina", "smtp.sina.com.cn");

		// tom
		hostMap.put("smtp.tom", "smtp.tom.com");

		// 263
		hostMap.put("smtp.263", "smtp.263.net");

		// yahoo
		hostMap.put("smtp.yahoo", "smtp.mail.yahoo.com");

		// hotmail
		hostMap.put("smtp.hotmail", "smtp.live.com");

		// gmail
		hostMap.put("smtp.gmail", "smtp.gmail.com");
		hostMap.put("smtp.port.gmail", "465");
		
		//abchk
		hostMap.put("smtp.receptionexpert", "smtp.abchk.com");
		hostMap.put("smtp.port.receptionexpert", "465");
	}

	/**
	 * 发送方邮件账号
	 */
	private String from;
	/**
	 * 邮件中显示发送方称呼
	 */
	private String fromName;
	/**
	 * 发送方邮件账号
	 */
	private String username;
	/**
	 * 发送方邮件账号密码
	 */
	private String password;
	
	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getFromName() {
		return fromName;
	}

	public void setFromName(String fromName) {
		this.fromName = fromName;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public MailHandler() {
	}
	
	public MailHandler(String from, String fromName, String username, String password) {
		this.from = from;
		this.fromName = fromName;
		this.username = username;
		this.password = password;
	}

	public String getHost(String email) throws Exception {
		Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
		Matcher matcher = pattern.matcher(email);
		String key = "unSupportEmail";
		if (matcher.find()) {
			key = "smtp." + matcher.group(1);
		}
		if (hostMap.containsKey(key)) {
			return hostMap.get(key);
		} else {
			throw new Exception("unSupportEmail");
		}
	}

	public int getSmtpPort(String email) throws Exception {
		Pattern pattern = Pattern.compile("\\w+@(\\w+)(\\.\\w+){1,2}");
		Matcher matcher = pattern.matcher(email);
		String key = "unSupportEmail";
		if (matcher.find()) {
			key = "smtp.port." + matcher.group(1);
		}
		if (hostMap.containsKey(key)) {
			return Integer.parseInt(hostMap.get(key));
		} else {
			return 25;
		}
	}


	/**
	 * 发送普通邮件
	 * 
	 * @param toMailAddr
	 *            收信人地址
	 * @param subject
	 *            email主题
	 * @param message
	 *            发送email信息
	 */
	public void sendMail(Email email) {
		StringBuffer log = new StringBuffer();
		log.append("\r\n------------------发送邮件------------------");
		HtmlEmail hemail = new HtmlEmail();
		try {
			hemail.setHostName(getHost(from));
			hemail.setSmtpPort(getSmtpPort(from));
			hemail.setCharset(CHARSET);
			hemail.addTo(email.getToMailAddr());
			hemail.setFrom(from, fromName);
			hemail.setAuthentication(username, password);
			hemail.setSubject(email.getSubject());
			hemail.setMsg(email.getMessage());
			log.append("\r\n发送方:\r\n");
			log.append(from);
			log.append("\r\n接收方:\r\n");
			log.append(email.getToMailAddr());
			log.append("\r\n结果:");
			hemail.send();
			log.append("\r\n发送成功");
		} catch (Exception e) {
			e.printStackTrace();
			log.append("\r\n发送失败");
		} finally{
			log.append("\r\n------------------发送完毕------------------");
			utilLogger.info(log.toString());
		}
	}


}